package com.example.exam.controller;

import com.example.exam.mapper.TUserMapper;
import com.example.exam.pojo.entity.TUser;
import com.example.exam.pojo.vo.UserVO.LoginVO;
import com.example.exam.service.impl.PwdToolsServiceIpml;
import com.example.exam.tools.JsonResult;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.Select;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.security.Key;

/**
 * @author LENOVO
 * @description TODO
 * @date 2023/4/4 1:11
 */
@RestController
@Slf4j
@Api(tags = "登入")
@RequestMapping("/api/user")
public class LoginUser {

    private final static String Key="123";

    @Autowired
    private PwdToolsServiceIpml pwdToolsServiceIpml;
    @Autowired
    private TUserMapper userMapper;

    @PostMapping("/login")
    public JsonResult login(@RequestBody LoginVO model, HttpServletRequest request){
        TUser tUser = userMapper.selectByName(model.getUserName());
        String encrypt="";
        if(!ObjectUtils.isEmpty(tUser)){
             encrypt = pwdToolsServiceIpml.decrypt(tUser.getPassword(),Key);
        }
        if(ObjectUtils.isEmpty(tUser)){
            return JsonResult.fail(-1,"用户不存在");
        }else if(!encrypt.equals(model.getPassword())||!tUser.getUserName().equals(model.getUserName())){
            return  JsonResult.fail(-1,"用户账号密码错误");
        }else {
             request.getSession().setAttribute("tUser",tUser);
            return  JsonResult.ok(1);
        }
    }
    @PostMapping("/logout")
    public JsonResult logout( HttpServletRequest request){
        request.removeAttribute("tUser");
            return  JsonResult.ok(1);
        }

}
